package indi.zn.commons.jaxb;



import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**  
*
*  
* @author 周楠
* @Description: 
* @date 2017年12月29日
*
*/
public class JaxbUtil {
	
	 public static String encoding="UTF-8";
	
	 public static String marshal(Object obj) {  
	        String result = null;  
	        try {  
	            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
	 
	            Marshaller marshaller = context.createMarshaller();  

	            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);  
	            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  
	  
	            StringWriter writer = new StringWriter();  
	            marshaller.marshal(obj, writer);  
	            result = writer.toString();  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  
	        return result;  
	    } 
	
	 
	 @SuppressWarnings("unchecked")  
	    public static <T> T unmarshaller(String xml, Class<T> c) {  
	        T t = null;  
	        try {  
	            JAXBContext context = JAXBContext.newInstance(c);  
	            Unmarshaller unmarshaller = context.createUnmarshaller();  
	            t = (T) unmarshaller.unmarshal(new StringReader(xml));  
	        } catch (Exception e) {  
	            e.printStackTrace();  
	        }  
	  
	        return t;  
	    }  
	
	 

}
